//
//  NotificationCocosSDK.swift
//  Game106Client-mobile
//
//  Created by Developer001 on 2025/5/15.
//

import Foundation
import AppTrackingTransparency
import AdSupport

@objc class NotificationCocosSDK : NSObject, SDKDelegate {
    
    // 静态变量持有单例实例
    @MainActor
    static var instance: NotificationCocosSDK?
    
    var viewController :UIViewController?
    
    let cloudStore = NSUbiquitousKeyValueStore.default
    
    @MainActor
    @objc func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        print("@NotificationCocosSDK launched")
        
        NotificationCocosSDK.instance = self
        
        if let window = application.delegate?.window {
            viewController = window?.rootViewController
        }
        
        JsbSDK.onMsg("NotificationCocosSDK.requestPermission", handler: self.requestPermission);
        JsbSDK.onMsg("NotificationCocosSDK.requestScheduleNotification", handler: self.requestScheduleNotification);
        JsbSDK.onMsg("NotificationCocosSDK.requestRemoveNotification", handler: self.requestRemoveNotification);
        
        return true
    }
    
    func requestPermission(args:String?) {
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
            if granted {
                print("Permission already got!")
            }
        }
    }
    
    func requestScheduleNotification(args:String?) {
        print("@requestScheduleNotification \(args!)")
        if let jsonData = args?.data(using: .utf8) {
            do {
                if let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
                    let identifier = json["identifier"] as? String ?? "custom"
                    let title = json["title"] as? String
                    let body = json["body"] as? String
                    let dateDouble = json["date"] as? Double
                    let date = Date(timeIntervalSince1970: dateDouble! / 1000)
                    print("@scheduleNotification \(date) \(dateDouble!)")
                        
                    let content = UNMutableNotificationContent()
                    content.title = title ?? "n/a"
                    content.body = body ?? "n/a"
                    
                    // 转换为 DateComponents
                    let components = Calendar.current.dateComponents(
                        [.year, .month, .day, .hour, .minute, .second],
                        from: date
                    )

                    // 创建单次通知
                    let trigger = UNCalendarNotificationTrigger(
                        dateMatching: components,
                        repeats: false
                    )
                    
                    // 移除之前的相同创建
                    UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [identifier])
                    
                    // 创建请求并注册到通知中心
                    let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
                    UNUserNotificationCenter.current().add(request) { error in
                        if let error = error {
                            print("通知注册失败：\(error)")
                        }
                    }
                }
            } catch {
                print("Error parsing JSON: \(error)")
            }
        }
    }
    
    func requestRemoveNotification(args:String?) {
        print("@requestRemoveNotification \(args!)")
        if let jsonData = args?.data(using: .utf8) {
            do {
                if let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
                    let identifier = json["identifier"] as? String ?? "custom"
                    UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [identifier])
                }
            } catch {
                print("Error parsing JSON: \(error)")
            }
        }
    }

}

